package cn.thornbird.orgsync.repository.specification;

import cn.thornbird.orgsync.entity.TaskDetail;
import cn.thornbird.orgsync.entity.status.ExecuteStatus;
import cn.thornbird.orgsync.vo.request.TaskDetailQueryRequest;
import lombok.AllArgsConstructor;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@AllArgsConstructor
public class TaskDetailSpecification extends BaseSpecification<TaskDetail> {

    private static final long serialVersionUID = -4759891690167479735L;

    private final TaskDetailQueryRequest taskDetailQueryRequest;

    @Override
    public Predicate toPredicate(Root<TaskDetail> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = new ArrayList<>();
        Date startDate = taskDetailQueryRequest.getStartDate();
        Date endDate = taskDetailQueryRequest.getEndDate();
        ExecuteStatus executeStatus = taskDetailQueryRequest.getExecuteStatus();
        predicates.add(criteriaBuilder.equal(root.get("taskId"), taskDetailQueryRequest.getTaskId()));
        predicates.add(createDatePredicates(root, criteriaBuilder, "planTime", startDate, endDate));
        if (executeStatus != null) {
            predicates.add(criteriaBuilder.equal(root.get("executeStatus"), executeStatus));
        }
        return toPredicate(criteriaBuilder, predicates);
    }
}
